<template>
  <div>
    <div class="params head-form">
      <el-form label-width="auto">
        <div class="params-form">
          <el-form-item label="核销状态">
            <el-select placeholder="请选择" v-model="params.cancelState" style="flex: 1" @change="init">
              <el-option v-for="(item, index) in verificationType" :value="Number(index)" :label="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联订单">
            <el-input style="flex: 1" @blur="init" @keyup.enter="init" v-model="params.orderCode" placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <div class="params-select">
              <el-select v-model="params.type" placeholder="请选择" style="width: 135px" @change="init">
                <el-option v-for="(item, index) in type" :label="item" :value="Number(index)" />
              </el-select>
              <collaborators-query v-model:model-value="params.partnerId" :type="params.type" @flushed="init" />
            </div>
          </el-form-item>
          <el-form-item label="编号">
            <el-input v-model="params.slipCode" placeholder="请输入编号" style="flex: 1" @keyup.enter="init" @blur="init" />
          </el-form-item>
          <el-form-item>
            <div class="params-select">
              <el-select v-model="params.moneyType" placeholder="请选择" style="width: 135px" @change="init">
                <el-option label="应付金额" :value="1" />
                <el-option label="已付金额" :value="2" />
                <el-option label="未付金额" :value="3" />
                <el-option label="本次应付金额" :value="5" />
              </el-select>
              <input-range v-model="params.amount" @change="init" />
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input placeholder="请输入" v-model="params.remark" @keyup.enter="init" @blur="init" />
          </el-form-item>
          <el-form-item label="收款账户">
            <el-input placeholder="请输入" v-model="params.account" @keyup.enter="init" @blur="init" />
          </el-form-item>
          <el-form-item label="创建人">
            <created-by v-model="params.createId" @change="init" />
          </el-form-item>
          <el-form-item label="添加时间">
            <el-date-picker
              v-model="params.date"
              :teleported="false"
              style="flex: 1"
              type="daterange"
              range-separator="—"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="init"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-space>
              <el-checkbox label="本次支付未支付" v-model="params.currentIsPay" @change="init"></el-checkbox>
              <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
              <el-button :icon="Download" type="primary" @click="exportTable"> 导出</el-button>
            </el-space>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="total">合计金额<span>（所有筛选记录）</span></div>
    <div class="amount">
      <div>
        应付金额：<span>￥{{ count.plainMoney }}</span>
      </div>
      <div>
        已付金额：<span>￥{{ count.inMoney }}</span>
      </div>
      <div>
        未付金额：<span>￥{{ count.outMoney }}</span>
      </div>
    </div>
    <div class="batch">
      <el-button type="primary" :disabled="!checkedList.length" @click="openBatchPay">批量支付</el-button>
    </div>
    <div class="table">
      <el-table :data="data" max-height="calc(100vh - 550px)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column prop="slipCode" label="编号" width="160" />
        <el-table-column prop="businessType" label="业务类型" />
        <el-table-column prop="partner" label="合作方" min-width="260" />
        <el-table-column prop="extend1" label="客户" min-width="200" />
        <el-table-column prop="remark" label="备注" min-width="200">
          <template #default="scope">
            <div class="desc">{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="收款账户" min-width="200">
          <template #default="scope">
            <div class="desc">
              {{ scope.row.payName }}{{ scope.row.account ? "-" + scope.row.account : ""
              }}{{ scope.row.accountName ? "-" + scope.row.accountName : "" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="city" label="核销状态" width="120">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.cancelState == 1">待核销</el-tag>
            <el-tag type="primary" v-else-if="scope.row.cancelState == 2">部分核销</el-tag>
            <el-tag type="success" v-else>已核销</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="应付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.plainMoney }}</template>
        </el-table-column>
        <el-table-column prop="address" label="已付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.inMoney }}</template>
        </el-table-column>
        <el-table-column prop="zip" label="未付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.outMoney }}</template>
        </el-table-column>
        <el-table-column prop="zip" label="本次应付金额" width="120">
          <template #default="scope"> ￥{{ scope.row.currentPlainMoney }}</template>
        </el-table-column>
        <el-table-column prop="addDate" label="添加时间" width="180" />
        <el-table-column prop="orderCode" label="关联单据" width="180" />
        <el-table-column label="操作" fixed="right" width="230">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="openDetail(scope.row)">详情</el-button>
            <el-button type="primary" link size="small" @click="toPath(scope.row)">支付流水</el-button>
            <!--            <el-button type="primary" link size="small" v-if="scope.row.outMoney > 0" @click="openPay(scope.row, false)"-->
            <!--              >去支付-->
            <!--            </el-button>-->
            <!-- <el-button type="primary" link size="small" v-if="scope.row.cancelState==1" @click="openDel(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
        <template #empty>
          <el-empty />
        </template>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="query.current"
        v-model:page-size="query.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="init"
        @current-change="init"
      />
    </div>
    <el-dialog v-model="detailVisible" width="500" center align-center :show-close="false">
      <template #title>
        <div class="modal-title">
          <custom-title title="采购付款单详情" />
          <el-icon @click="detailVisible = false">
            <Close />
          </el-icon>
        </div>
      </template>
      <div class="detail">
        <div>
          <div>
            采购付款单编码：<span class="black">{{ detail.slipCode }}</span>
          </div>
          <el-tag type="warning" v-if="detail.cancelState == 1">待核销</el-tag>
          <el-tag type="primary" v-else-if="detail.cancelState == 2">部分核销</el-tag>
          <el-tag type="success" v-else>已核销</el-tag>
        </div>
        <div>
          关联合作方<span class="black">{{ detail.partner }}</span>
        </div>
        <div>
          关联订单<span class="black">{{ detail.orderCode }}</span>
        </div>
        <div>
          应付金额<span class="black">￥{{ detail.plainMoney }}</span>
        </div>
        <div>
          已付金额<span class="black">￥{{ detail.inMoney }}</span>
        </div>
        <div>
          未付金额<span class="black">￥{{ detail.outMoney }}</span>
        </div>
        <!-- <div>
                    未使用金额<span class="black">￥{{ detail.notUseMoney }}</span>
                </div> -->
      </div>
    </el-dialog>
    <!--    start 批量支付-->
    <div class="pay-dialog">
      <add-pay-dialog
        :selectSlipCodes="selectSlipCodes"
        :partnerAccountId="detail.partnerAccountId"
        v-model="payVisible"
        v-if="payVisible"
        @handleSavePay="init"
      ></add-pay-dialog>
    </div>
    <!--    end 批量支付-->
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { RefreshRight, Download } from "@element-plus/icons-vue";
import { getList, getCount, exportTableData } from "@/apis/invoices";
import { ElMessage } from "element-plus";
import { type, verificationType } from "@/utils/config";
import { useRoute } from "vue-router";
import exportExcel from "@/utils/exportExcel";
import AddPayDialog from "./AddPayDialog.vue";

const route = useRoute();

const emit = defineEmits(["toPayment"]);
const toPath = item => {
  emit("toPayment", {
    slipCode: item.slipCode,
    slipType: 2
  });
};

const checkedList = ref([]);
const query = ref({
  current: 1,
  size: 10
});

const params = ref({
  serviceType: 2,
  slipCode: route.query.slipCode,
  currentIsPay: true
});
const reset = () => {
  params.value = {
    serviceType: 2
  };
  init();
};

const detailVisible = ref(false);
const payVisible = ref(false);

const detail = ref({});
const total = ref(0);
const data = ref([]);
const count = ref({
  outMoney: 0,
  inMoney: 0,
  plainMoney: 0
});
const isBatch = ref(false);

const openDetail = item => {
  detailVisible.value = true;
  detail.value = { ...item };
};

/**
 * 打开支付弹窗
 */

const openPay = async (item, batch) => {
  // isImgMax.value = false;
  isBatch.value = batch;
  payVisible.value = true;
  detail.value = { ...item };
};

const getParams = () => {
  const minAmount = params.value.amount ? params.value.amount[0] : undefined;
  const maxAmount = params.value.amount ? params.value.amount[1] : undefined;
  const createdTimeBegin = params.value.date ? params.value.date[0] + " 00:00:00" : undefined;
  const createdTimeEnd = params.value.date ? params.value.date[1] + " 23:59:59" : undefined;
  const currentIsPay = params.value.currentIsPay ? 1 : undefined;
  const paramsData = {
    ...params.value,
    minAmount,
    maxAmount,
    createdTimeBegin,
    createdTimeEnd,
    currentIsPay
  };
  delete paramsData.date;
  delete paramsData.amount;
  return paramsData;
};
/**
 * 初始化
 */
const init = async () => {
  const res = await getList(query.value, getParams());
  data.value = res.data.list;
  total.value = res.data.total;
  const counts = await getCount(getParams());
  count.value = counts.data ? counts.data : { outMoney: 0, inMoney: 0, plainMoney: 0 };
};
const exportTable = async () => {
  try {
    const res = await exportTableData(query.value, getParams());
    exportExcel(res, "采购付款单列表");
  } catch (error) {}
};

/**
 * 选择
 */
const handleSelectionChange = newSelection => {
  checkedList.value = newSelection;
};
const selectSlipCodes = computed(() => {
  return checkedList.value.length && checkedList.value.map(v => v.slipCode);
});
/**
 * 打开批量弹窗
 */
const openBatchPay = () => {
  if (!checkedList.value.every(v => v.partnerId == checkedList.value[0].partnerId))
    return ElMessage.error("只能相同供应商且相同收款账户可以批量支付，若有特殊需要请单条进行支付！");
  if (!checkedList.value.every(v => v.partnerAccountId == checkedList.value[0].partnerAccountId))
    return ElMessage.error("只能相同供应商且相同收款账户可以批量支付，若有特殊需要请单条进行支付！");
  if (checkedList.value.some(v => v.cancelState == 3)) {
    return ElMessage.error("请选择未核销的数据");
  }

  openPay(
    {
      ...checkedList.value[0],
      slipCode: checkedList.value.map(v => v.slipCode).join(","),
      plainMoney: checkedList.value.reduce((a, b) => a + Number(b.plainMoney), 0).toFixed(2),
      inMoney: checkedList.value.reduce((a, b) => a + Number(b.inMoney), 0).toFixed(2),
      currentPlainMoney: checkedList.value.reduce((a, b) => a + Number(b.currentPlainMoney), 0).toFixed(2),
      slipId: checkedList.value.map(v => v.slipId)
    },
    true
  );
};

onMounted(() => {
  init();
});
</script>

<style lang="scss">
.pay-dialog {
  .el-dialog {
    display: flex !important;
    flex-direction: column !important;
  }
  .el-dialog__body {
    flex: 1 !important;
    overflow-y: auto !important;
  }
}
</style>
<style lang="scss" scoped>
@import "../../comon";
</style>
